import Http from '@/utils/requset'
export function randomWord (randomFlag, number) {
  // 生成图片名称
  let str = ''; let range = number; let pos = ''
  const arr = [
    '0',
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    'A',
    'B',
    'C',
    'D',
    'E',
    'F',
    'G',
    'H',
    'I',
    'J',
    'K',
    'L',
    'M',
    'N',
    'O',
    'P',
    'Q',
    'R',
    'S',
    'T',
    'U',
    'V',
    'W',
    'X',
    'Y',
    'Z'
  ]
  if (randomFlag) {
    range = Math.round(Math.random()) + number
  }
  for (let i = 0; i < range; i++) {
    pos = Math.round(Math.random() * (arr.length - 1))
    str += arr[pos]
  }
  return str
}

export const ossConfig = (path) => {
  const nameStr = `img/${randomWord(
    true,
    20
  )}${new Date().valueOf()}${path.substr(path.lastIndexOf('.'))}`
  return new Promise((resolve, reject) => {
    Http({
      url: '/common/oss/config',
      type: ''
    }).then(result => {
      if (result.code === 0) {
        uni.uploadFile({
          url: result.data.endpoint,
          filePath: path,
          name: 'file',
          formData: {
            key: nameStr,
            policy: result.data.policy, // 输入你获取的的policy
            OSSAccessKeyId: result.data.accessKeyId, // 输入你的AccessKeyId
            success_action_status: 200, // 让服务端返回200,不然，默认会返回204
            signature: result.data.signature // 输入你获取的的signature
          },
          success: (res) => {
            if (res.statusCode === 200) {
              resolve('https://img.qumoyugo.com/' + nameStr)
            } else {
              uni.showToast({
                title: '上传失败',
                icon: 'none'
              })
              Promise.reject(new Error('上传失败'))
            }
          },
          fail: () => {
            uni.showToast({
              title: '上传失败',
              icon: 'none'
            })
            Promise.reject(new Error('上传失败'))
          }
        })
      } else {
        uni.showToast({
          title: '图片上传失败',
          icon: 'none'
        })
        Promise.reject(new Error('图片上传失败'))
      }
    })
  })
}
